﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using Facebook;
using QuizzMe.Helpers;
using QuizzMe.Model;
using QuizzMe.QuizzServiceRef;

namespace QuizzMe.Pages
{
    /// <summary>
    /// QuizzMe TopTen page
    /// </summary>
    public partial class TopTen : BasePage
    {
        private VRank _currentPlayer;

        public ObservableCollection<VRank> List
        {
            get; set;
        }

        public TopTen()
        {
            InitializeComponent();
        }

        private void OnClientOnGetTopTenCompleted(object sender, GetTopTenCompletedEventArgs args)
        {
            ServiceClientHelper.Client.GetTopTenCompleted -= OnClientOnGetTopTenCompleted;
            ObservableCollection<User> users = args.Result;
            
            List = new ObservableCollection<VRank>(users.OrderByDescending(u => u.score).Select(u => new VRank(u.fbId.ToString(), u.score)));
            int i = 1;
            foreach (VRank vRank in List)
            {
                vRank.Rank = i++;
            }

            GetNames();
        }

        private void GetNames()
        {
            _currentPlayer = List.FirstOrDefault(v => string.IsNullOrEmpty(v.Name));
            if (_currentPlayer != null)
            {
                Fb fb = AuthHelper.Get.FacebookClient;
                fb.AddHandler(FbGetCompleted);
                fb.GetAsync(_currentPlayer.FbId);
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                                           {
                                               OnPropertyChanged("List");
                                               Loading = false;
                                           });
            }
        }

        private void FbGetCompleted(object sender, FacebookApiEventArgs e)
        {
            VRank currentVRank = _currentPlayer;

            dynamic res = e.GetResultData();
            currentVRank.Name = res.name;
              
            GetNames();
        }

        private void ButtonBackClick(object sender, RoutedEventArgs e)
        {
            this.NavigateTo("/Home");
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Loading = true;
            ServiceClientHelper.Client.GetTopTenCompleted += OnClientOnGetTopTenCompleted;
            ServiceClientHelper.Client.GetTopTenAsync();
        }
    }
}
